package com.tuanzhang.mall.goods.domain.factory;

import cn.hutool.core.util.IdUtil;
import com.tuanzhang.mall.goods.domain.aggregate.Spu;
import com.tuanzhang.mall.goods.domain.valueobj.*;
import com.tuanzhang.mall.goods.types.req.SpuSaveParam;
import com.tuanzhang.mall.goods.types.req.UserApiVO;
import com.tuanzhang.mall.seller.domain.valueobj.PhoneNumber;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SpuFactory {


    public static Spu createSpuFromParam(SpuSaveParam spuSaveParam, UserApiVO userApiVO) {
        PhoneNumber phoneNumber = PhoneNumber.create(userApiVO.getPhoneNumber());
        SpuCode spuCode = SpuCode.getSpuCode(IdUtil.getSnowflakeNextId());
        Category category = Category.create(spuSaveParam.getCategoryId());

        List<Sku> skus = new ArrayList<>();
        List<SpuSaveParam.Sku> skuList = spuSaveParam.getSkuList();


        final BigDecimal[] maxPrice = {BigDecimal.ZERO};
        final BigDecimal[] minPrice = {BigDecimal.ZERO};
        skuList.forEach(v -> {
            Money money = Money.getMoney(v.getPrice(), spuSaveParam.getPriceType());
            SkuCode skuCode = SkuCode.getSkuCode(IdUtil.getSnowflakeNextId());

            List<Spec> skuSpecList = new ArrayList<>();
            List<SpuSaveParam.Sku.Spec> specList = v.getSpec();
            specList.forEach(specInfo -> {
                SpuSaveParam.Sku.SpecItem item = specInfo.getItem();
                SpecItem specItem = SpecItem.createSpecItem(item.getId(), item.getValue());
                Spec spec = Spec.createSpec(specInfo.getId(), specInfo.getSpec(), specItem);
                skuSpecList.add(spec);
            });

            Inventory inventory = Inventory.getQuantity(v.getStock());
            Sku sku = Sku.createSku(skuCode, skuSpecList, money, spuSaveParam.getSaleMinNum(), inventory);
            skus.add(sku);

            if (maxPrice[0].compareTo(BigDecimal.ZERO) == 0 || maxPrice[0].compareTo(money.getAmount()) < 0) {
                maxPrice[0] = money.getAmount();
            }

            if (minPrice[0].compareTo(BigDecimal.ZERO) == 0 || minPrice[0].compareTo(money.getAmount()) > 0) {
                minPrice[0] = money.getAmount();
            }

        });

        Money maxMoney = Money.getMoney(maxPrice[0], spuSaveParam.getPriceType());
        Money minMoney = Money.getMoney(minPrice[0], spuSaveParam.getPriceType());

        MoneyRange moneyRange = MoneyRange.getMoneyRange(maxMoney, minMoney);

        return Spu.createSpu(spuCode, phoneNumber, spuSaveParam.getSpuName(), Arrays.asList(spuSaveParam.getSpuImages().split(",")),category, moneyRange, skus, false);
    }

}
